from datetime import datetime,timezone, timedelta
from io import BytesIO
import os
import tempfile
import uuid
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from dingtalk_service.yida_client_base import YidaClientBase
from yida_app_service.models import HzfwQrCode
from yida_app_service.utils.hzfw_utils import gen_qr_code, update_report_info
from reportservice.helpers import ApiResponse
import json
import requests
import qrcode
from reportlab.pdfgen import canvas
from PyPDF2 import PdfWriter, PdfReader
from reportlab.lib.utils import ImageReader
from oss_service.views import bucket
from io import BytesIO
from datetime import datetime
from yida_app_service.views import get_xm_client, get_yida_client
from yida_app_service.xu_cloud_client import XmCloudBaseClient


@csrf_exempt
@require_http_methods(["POST"])
def apply_hzfw_qr_ex(request,company_name):
    datasource: dict[str, any] = json.loads(request.body)
    report_code = datasource["reportCode"]
    YidaClient = get_yida_client(company_name)
    yida_client:YidaClientBase = YidaClient()
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    current_date = datetime.now().strftime("%Y%m%d")
    temp_file_name = f"file_tmp/{current_date}/{uuid.uuid4()}.png"
    qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=xm_client.hzfw_org_id, is_uploaded=False).order_by('-id').first()
    if not qr_code:
        try:
            res = gen_qr_code(xm_client.hzfw_org_id, report_code)
        except Exception as e:
            return ApiResponse.fail(message=f"生成二维码失败,{e}")
        if res["code"] == "ok":
            qr_data = res["qrcodestr"]
            qr_code = HzfwQrCode(report_code=report_code,
                                    org_id=xm_client.hzfw_org_id,
                                    company_name=company_name,
                                    qr_code_content=qr_data)
            qr_code.save()
    qr_data = qr_code.qr_code_content
    qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=4,
            )
    qr.add_data(qr_data)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
    datas = img.getdata()
    newData = []
    for item in datas:
        # 改变白色背景为透明
        if item[:3] == (255, 255, 255):
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
    img.putdata(newData)
    qr_io = BytesIO()
    img.save(qr_io, format="PNG")
    qr_io.seek(0)  # 移动到流的开头
    bucket.put_object(temp_file_name,qr_io)
    url = bucket.sign_url("GET",temp_file_name,3600)
    return ApiResponse.success(url)
        

@csrf_exempt
@require_http_methods(["POST"])
def apply_hzfw_qr(request,company_name):
    datasource: dict[str, any] = json.loads(request.body)
    report_code = datasource["reportCode"]
    file_url = datasource["fileUrl"]
    default_position = [{
                          "page":1,
                          "posx":50,
                          "posy":50,
                          "size":100
                      }]
    positions = datasource.get("position",default_position)
    YidaClient = get_yida_client(company_name)
    yida_client:YidaClientBase = YidaClient()
    full_download_url = yida_client.get_full_download_url(
        user_id=yida_client.admin_user_id, download_url=file_url)
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        pdf_content = BytesIO(response.content)
        XmCloudClient = get_xm_client(company_name)
        xm_client:XmCloudBaseClient = XmCloudClient()
        qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=xm_client.hzfw_org_id, is_uploaded=False).order_by('-id').first()
        if not qr_code:
            try:
                res = gen_qr_code(xm_client.hzfw_org_id, report_code)
            except Exception as e:
                return ApiResponse.fail(message=f"生成二维码失败,{e}")
            if res["code"] == "ok":
                qr_data = res["qrcodestr"]
                qr_code = HzfwQrCode(report_code=report_code,
                                      org_id=xm_client.hzfw_org_id,
                                      company_name=company_name,
                                      qr_code_content=qr_data)
                qr_code.save()
        qr_data = qr_code.qr_code_content
        reprt_pdf = PdfReader(pdf_content)
        output = PdfWriter()
        for position in positions:
            page_num = int(position["page"])
            qr_x = int(position["posx"])
            qr_y = int(position["posy"])
            qr_size = int(position["size"])
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=4,
            )
            qr.add_data(qr_data)
            qr.make(fit=True)
            img = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
            datas = img.getdata()
            newData = []

            for item in datas:
                # 改变白色背景为透明
                if item[:3] == (255, 255, 255):
                    newData.append((255, 255, 255, 0))
                else:
                    newData.append(item)
            img.putdata(newData)
            qr_io = BytesIO()
            img.save(qr_io, format="PNG")
            qr_io.seek(0)  # 移动到流的开头
            if page_num - 1 < len(reprt_pdf.pages):
                current_page = reprt_pdf.pages[page_num-1]
                # 绘制 QR 码至指定页面
                packet = BytesIO()
                page_width = current_page.mediabox.width
                page_height = current_page.mediabox.height
                c = canvas.Canvas(packet, pagesize=(page_width, page_height))
                qr_image = ImageReader(qr_io)
                c.drawImage(qr_image, qr_x, qr_y, qr_size, qr_size,mask='auto')
                c.save()

                # 合并 QR 码页面到原始 PDF 页面
                packet.seek(0)
                qr_pdf = PdfReader(packet)
                reprt_pdf.pages[page_num - 1].merge_page(qr_pdf.pages[0])
        for page in reprt_pdf.pages:
            output.add_page(page)
        UUID = uuid.uuid4()
        pdf_path = f'yida-app/{company_name}/reports/{UUID}.pdf'
        with tempfile.TemporaryDirectory() as temp_dir:
            tmp_path = os.path.join(temp_dir,pdf_path)
            if not os.path.exists(os.path.dirname(tmp_path)):
                os.makedirs(os.path.dirname(tmp_path))
            with open(tmp_path, "wb") as outputStream:
                output.write(outputStream)
            bucket.put_object_from_file(pdf_path, tmp_path)
            qr_code.pdf_path = pdf_path
            qr_code.save()
        sign_url = bucket.sign_url('GET', pdf_path, 3600)
        return ApiResponse.success(sign_url)
    else:
        return ApiResponse.fail(res["msg"])

def date_format(value,default_str=None):
    try:
        date = datetime.fromtimestamp(int(value) / 1000, timezone.utc)
        date += timedelta(hours=8)
        return date.strftime('%Y-%m-%d')
    except ValueError:
        return default_str

@csrf_exempt
@require_http_methods(["POST"])
def upload_hzfw_data(request,company_name):
    datasource = json.loads(request.body)
    try:
        area_name = datasource.get("area_name","市辖区")
        req_info = datasource["report_info"]
        report_code = datasource["report_code"]
        report_info = {}
        report_info["GCMC"] = req_info.get("GCMC","-")
        report_info["YPBH"] = req_info.get("YPBH","-")
        report_info["WTDW"] = req_info.get("WTDW","-")
        report_info["JCNR"] = req_info.get("JCNR","-")
        report_info["JCJL"] = req_info.get("JCJL","-")
        report_info["BGRQ"] = date_format(req_info.get("BGRQ","-"),"-")
        report_info["JCRQ"] = date_format(req_info.get("JCRQ","-"),None)
        if not report_info["JCRQ"]:
            return ApiResponse.fail("检测日期错误",400)
        if req_info.get("JCRQ2"):
            report_info["JCRQ2"]  = date_format(req_info["JCRQ2"])
        XmCloudClient = get_xm_client(company_name)
        xm_client:XmCloudBaseClient = XmCloudClient()
        res = update_report_info(xm_client.hzfw_org_id,"",area_name,report_code,report_info)
        if "上传成功" in res:
            qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=xm_client.hzfw_org_id, is_uploaded=False).order_by('-id').first()
            qr_code.is_uploaded = True
            qr_code.save()
            return ApiResponse.success(res)
        else:
            return ApiResponse.fail(res,400)
    except KeyError:
        return ApiResponse.fail("字段必传校验失败",400)
    

@csrf_exempt
@require_http_methods(["GET"])
def download_hzfw_pdf(request,company_name):
    report_code = request.GET.get("report_code")
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=xm_client.hzfw_org_id).order_by('-id').first()
    if qr_code:
        pdf_path = qr_code.pdf_path
        if pdf_path:
            sign_url = bucket.sign_url('GET', pdf_path, 3600)
            return redirect(sign_url)
    return ApiResponse.fail("未找到报告",404)